<template>
  <tw-modal
    :visible="visible"
    @close="closeAuthModal"
    class="tw-secondary-validation xsmall"
  >
    <template slot="header">账号验证</template>
    <template slot="body">
      <div class="tw-flex justify-content-center">
        <el-alert
          class="tw-alert-info"
          :title=" formData.type===1?'请输入验证码进行二次校验':
            (step === 1
              ? '你的账号未绑定手机号码,该操作将进行手机与账号的绑定,并完成双因子认证.'
              : '请输入手机验证码进行二次校验')
          "
          type="info"
          show-icon
          :closable="false"
        >
        </el-alert>
      </div>

      <el-form
        ref="doubleAuthForm"
        style="margin-top: 30px"
        :model="formData"
        :rules="step === 1 ? formRulesStep1 : formRulesStep2"
        label-width="100px"
        label-position="right"
      >
        <el-form-item v-if="!hasBindMobile"
          label="验证方式:"
          prop="type"
          class="secondary-validation-phone"
        >
          <el-radio-group v-model="formData.type">
            <el-radio :label="0">手机验证</el-radio>
            <el-radio :label="1">邮箱验证</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          :label="formData.type===1?'邮箱地址:':'手机号码:'"
          prop="address"
          class="secondary-validation-phone"
        >
          <template v-if="formData.type===1">
            <el-input
              v-if="step === 1"
              v-model="formData.address"
              :placeholder="formData.type===1?'请输入邮箱地址':'请输入手机号'"
            ></el-input>
            <span v-else>{{
              $app.user.loginMobile.replace(/(\d{3})\d{4}(\d{4})/, "$1****$2")
            }}</span>
          </template>
          <template v-else>
            <el-input
              v-if="step === 1"
              v-model="formData.address"
              placeholder="请输入手机号"
              :maxlength="11"
            ></el-input>
            <span v-else>{{
              $app.user.loginMobile.replace(/(\d{3})\d{4}(\d{4})/, "$1****$2")
            }}</span>
          </template>
        </el-form-item>
        <el-form-item label="验证码:" prop="code">
          <div class="code">
            <el-input
              style="flex: 1"
              v-model="formData.code"
              placeholder="请输入验证码"
            >
              <template slot="suffix">
                <a class="text-btn" v-if="showGetCode" @click="getSmsCode"
                  >获取验证码</a
                >
                <span class="xgray" v-else>{{ countDownTimes }}s</span>
              </template>
            </el-input>
          </div>
        </el-form-item>
      </el-form>
    </template>
    <template slot="footer">
      <el-button
        type="primary"
        class="tw-ele-button" @click="handleSubmitTap">提交</el-button>
      <el-button
        type="primary"
        class="tw-ele-button xweaking" @click="closeAuthModal">返回</el-button>
    </template>
  </tw-modal>
</template>

<script>
export default {
  name: 'secondary-validation',
  props: {
    visible: {
      type: Boolean,
      default: false,
      required: true
    }
  },
  data () {
    return {
      title: '',
      formData: {
        type: 0,
        address: '',
        code: ''
      },
      formRulesStep1: {
        address: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { min: 11, max: 11, message: '请输入正确的手机号码', trigger: 'blur' }
        ],
        code: [{ required: true, message: '请输入验证码', trigger: 'blur' }]
      },
      formRulesStep2: {
        code: [{ required: true, message: '请输入验证码', trigger: 'blur' }]
      },
      showGetCode: true,
      countDownTimes: 60,
      sending: false
    }
  },
  computed: {
    innerVisible: {
      get () {
        return this.visible
      },
      set (val) {
        return this.$emit('update:visible', val)
      }
    },
    hasBindMobile () {
      if (
        window.$app.user &&
        window.$app.user.loginMobile &&
        !window.$ui.isEmptyValue(window.$app.user.loginMobile)
      ) {
        return true
      }
      return false
    },
    step () {
      if (
        window.$app.user &&
        window.$app.user.loginMobile &&
        !window.$ui.isEmptyValue(window.$app.user.loginMobile)
      ) {
        return 2
      }
      return 1
    }
  },
  methods: {
    getSmsCode () {
      let pass = true
      if (this.step === 1) {
        this.$refs.doubleAuthForm.validateField('address', errorMsg => {
          if (errorMsg) {
            pass = false
          }
        })
      } else {
        this.formData.address = window.$app.user.loginMobile
      }

      if (pass) {
        const { user } = window.$app
        const params = {
          address: this.formData.address,
          type: this.formData.type, // 0,
          userId: user.userId
        }
        let phone = this.formData.address.replace(
          /(\d{3})\d{4}(\d{4})/,
          '$1****$2'
        )

        this.$axios
          .post(`${window.$app.eco.gateway}/openapi-uc/f2a/sendCode`, params, {
            headers: {
              'Access-Token': user.token,
              'Tenant-Id': user.branchCode || 'twsaas'
            }
          })
          .then(resp => {
            if (resp && resp.data.serverResult.resultCode === '200') {
              this.$message({
                message: `已发送验证码至手机号:${phone},请注意查收`,
                type: 'success'
              })
              this.sending = false
            } else {
              this.$message({
                message:
                  (resp &&
                    resp.data &&
                    resp.data.serverResult &&
                    resp.data.serverResult.resultMessage) ||
                  '获取验证码失败',
                type: 'error'
              })
            }
          })
          .catch(error => {
            // if (error.data.serverResult.resultCode === '400') {
            this.$message({
              message:
                (error &&
                  error.data &&
                  error.data.serverResult.resultMessage) ||
                '获取验证码失败',
              type: 'error'
            })
            // }
          })

        this.showGetCode = false

        if (this.timer) {
          clearInterval(this.timer)
          this.countDownTimes = 60
          this.timer = null
        }
        this.timer = setInterval(() => {
          this.countDownTimes--
          if (this.countDownTimes === 0) {
            this.showGetCode = true
            clearInterval(this.timer)
            this.countDownTimes = 60
          }
        }, 1000)
      }
    },

    closeAuthModal () {
      this.innerVisible = false
      Object.assign(this.$data, this.$options.data())
    },

    handleSubmitTap () {
      this.$refs.doubleAuthForm.validate(valid => {
        if (valid) {
          const { user } = window.$app
          const params = {
            address: this.formData.address,
            type: this.formData.type, // 0,
            userId: user.userId,
            code: this.formData.code
          }
          this.$axios
            .post(`${window.$app.eco.gateway}/openapi-uc/f2a/access`, params, {
              headers: {
                'Access-Token': user.token,
                'Tenant-Id': user.branchCode || 'twsaas'
              }
            })
            .then(resp => {
              if (
                resp &&
                resp.data.serverResult.resultCode === '200' &&
                resp.data.responseEntity &&
                resp.data.responseEntity.s2FAC
              ) {
                const doubleAuthenticParamas = JSON.parse(
                  localStorage.getItem('doubleAuthenticParamas')
                )
                let key = doubleAuthenticParamas.username + '_S2FAC'
                localStorage.setItem(key, resp.data.responseEntity.s2FAC)
                localStorage.setItem('doubleAuthentic', '0')
                this.$emit('succeed', user)
                this.closeAuthModal()
              } else {
                this.$message({
                  message:
                    (resp &&
                      resp.data &&
                      resp.data.serverResult &&
                      resp.data.serverResult.resultMessage) ||
                    '账号认证失败',
                  type: 'error'
                })
              }
            })
            .catch(error => {
              let msg = '账号认证失败'
              if (
                error &&
                error.data &&
                error.data.serverResult &&
                error.data.serverResult.resultMessage
              ) {
                msg = error.data.serverResult.resultMessage
              }
              this.$message({
                message: msg,
                type: 'error'
              })
            })
        }
      })
    }
  },

  beforeDestroy () {
    window.$ui.cookie.delete('webauthorized')
  }
}
</script>

<style lang="scss">
.tw-secondary-validation .code {
  display: flex;
  align-items: center;
  a {
    color: $color-main;
  }
}
.tw-secondary-validation .el-input__suffix-inner {
  height: 100%;
  display: flex;
  align-items: center;
}
.tw-alert-info .el-alert__content {
  padding-left: 16px;
}

.tw-alert-info {
  background: #f2f9ff !important;
  font-size: 14px !important;
  color: #333 !important;
  display: inline-flex !important;
  width: auto !important;
}

.tw-alert-info .el-alert__title {
  font-size: 14px;
  color: #333;
}

.tw-secondary-validation .el-form-item .el-form-item__content {
  line-height: 36px;
}
.tw-secondary-validation .el-form {
  margin-right: 20px;
}
</style>
